<?php

namespace App\Utility;

class MyFunc
{

    //验证 是否为空
    public static function is_empty($value){
        if(!isset($value) || empty($value)) return true;
        return false;
    }
    //验证 字符串长度
    public static function is_len($str, $len=0, $type='>'){
        if(!isset($str)) return false;
        $str_len = iconv_strlen($str,"UTF-8");
        if($type == '>' && $str_len>$len)  return true;
        if($type == '=' && $str_len==$len) return true;
        if($type == '<' && $str_len<$len)  return true;
        return false;
    }

    //负数取0
    public static function to_positive($num){
        $num = floatval($num);
        if($num<0) return 0;
        return $num;
    }

    //生成用户TOKEN
    public static function user_token(){
        return md5(uniqid(microtime(true),true).rand(100000,999999));
    }
    //生成订单号
    public static function order_sn() {
        // $order_no = date('YmdHis'). substr(microtime(), 2, 5) . sprintf('%02d', rand(100000, 999999));
        // $order_no = date('ymdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
      return date('ymdHis').str_pad(mt_rand(1, 99999999), 8, '0', STR_PAD_LEFT);
    }
    //生成固定长度字符串
    public static function rand_str($length=6, $type='num')   
    {   
        $key = '';
        $pattern = '0123456789';
        if($type == 'char') $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        if($type == 'lowerchar') $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';  
        for($i=0;$i<$length;$i++) $key .= $pattern{mt_rand(0, iconv_strlen($pattern,"UTF-8")-1)};    //生成php随机数  
        return $key;   
    }
    //随机生成国内ip
    public static function rand_ip(){
        $ip_long = array(
            array('607649792', '608174079'),
            array('1038614528', '1039007743'),
            array('1783627776', '1784676351'),
            array('2035023872', '2035154943'),
            array('2078801920', '2079064063'),
            array('-1950089216', '-1948778497'),
            array('-1425539072', '-1425014785'),
            array('-1236271104', '-1235419137'),
            array('-770113536', '-768606209'),
            array('-569376768', '-564133889'),
        );
        $rand_key = mt_rand(0, 9);
        return $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
    }

    //检查url是否能请求
    public static function url_exists($url)
    {
        $arr = get_headers($url,1);
        if(preg_match('/200/',$arr[0])){
            return true;
        }else{
            return false;
        }
    }
    //短链生成
    public static function short_url($long_url, $type='sina'){
        /*
        木子短链
        http://muzidwz.cn/sina_short.php?data=http://www.baidu.com
        http://muzidwz.cn/tencent.jason?data=http://www.baidu.com
        蓝鸟短链
        http://lnurl.cn/sina/short-api?url_long=http://www.baidu.com
        http://lnurl.cn/weixin/short-api?url_long=http://www.baidu.com
        冷狗短链
        http://dogdwz.cn/tcnjson?url_long=http://www.baidu.com
        http://dogdwz.cn/txjson?url_long=http://www.baidu.com
         */
        if($type == 'sina')   $api_url = "http://dogdwz.cn/tcnjson?url_long=".$long_url;
        if($type == 'wechat') $api_url = "http://dogdwz.cn/txjson?url_long=".$long_url;

        $rs = curl_hack($api_url);
        return $rs;
    }
    //微信安全域名检测
    public static function wechat_check_safe($url){
        $api_url = "http://www.xiaohejc.cn/check_api.php?url_long={$url}";
        $rs = file_get_contents($api_url);
        //$rs = curl_hack($api_url);
        return $rs;
    }
    //银行卡号检测
    public static function bankno_check($bankNo=''){
        $url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?cardNo={$bankNo}&cardBinCheck=true";
        $rs = curl_hack($url);
        $rs = json_decode($rs, true);
        if($rs['validated'] == false) return false;
        return ['bank'=>strtolower($rs['bank'])];
    }


    /**
    * 简单对称加密算法之加密
    * @param String $string 需要加密的字串
    * @param String $skey 加密EKY
    * @return String
    */
    public static function to_encode($string = '', $skey = 'bt18a9X01Dt') {
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
        $key < $strCount && $strArr[$key].=$value;
        return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
    }
    /**
    * 简单对称加密算法之解密
    * @param String $string 需要解密的字串
    * @param String $skey 解密KEY
    * @return String
    */
    public static function to_decode($string = '', $skey = 'bt18a9X01Dt') {
        $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
        $key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        return base64_decode(join('', $strArr));
    }

    //curl获取内容
    public static function curl_hack($url){
        $ch2 = curl_init();
        $user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";//模拟windows用户正常访问
        curl_setopt($ch2, CURLOPT_URL, $url);
        curl_setopt($ch2, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch2, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.rand_ip(), 'CLIENT-IP:'.rand_ip()));
        //追踪返回302状态码，继续抓取
        // curl_setopt($ch2, CURLOPT_HEADER, true); 
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($ch2, CURLOPT_NOBODY, false);
        curl_setopt($ch2, CURLOPT_REFERER, 'http://'.rand_ip());//模拟来路
        curl_setopt($ch2, CURLOPT_USERAGENT, $user_agent);
        $temp = curl_exec($ch2);
        curl_close($ch2);
        return $temp;
    }

    //时间函数
    public static function for_timestamp($type='day'){
        //php获取今日开始时间戳和结束时间戳
        if($type == 'day'){
            $start = mktime(0,0,0,date('m'),date('d'),date('Y'));
            $end   = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        }
        //php获取昨日起始时间戳和结束时间戳
        if($type == 'yesterday'){
            $start = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
            $end   = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        }
        //php获取本周起始时间
        if($type == 'week'){
            $start = mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y"));
            $end   = mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));
        }
        //php获取上周起始时间戳和结束时间戳
        if($type == 'lastweek'){
            $start = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
            $end   = mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
        }
        //php获取本月起始时间戳和结束时间戳
        if($type == 'month'){
            $start = mktime(0,0,0,date('m'),1,date('Y'));
            $end   = mktime(23,59,59,date('m'),date('t'),date('Y'));
        }
        //php获取本年起始时间戳和结束时间戳
        if($type == 'year'){
            $start = mktime(0,0,0,1,1,date('Y'));
            $end   = mktime(23,59,59,12,30,date('Y'));
        }
        return ['start'=>$start, 'end'=>$end];
    }




    /**
     * 数据库操作快捷方法 --- start --- //
     */
    //字段增加
    public static function db_field_inc($table, $where, $field='', $num=1){
        $num = $num >= 0 ? "+{$num}" : "{$num}";
        db($table)->where($where)->setInc($field, $num);
        return true;
    }
    //获取单个字段信息
    public static function db_get_field($table, $where, $field){
        return db($table)->where($where)->value($field);
    }
    //获取单行记录
    public static function db_get_row($table, $where){
        return db($table)->where($where)->find();
    }
    //获取多行记录
    public static function db_get_all($table, $where){
        return db($table)->where($where)->select();
    }
    //插入单行记录
    public static function db_add_row($table, $data){
        $_insertId = db($table)->strict(false)->insertGetId($data);
        return $_insertId;
    }
    //插入记录,存在则替换
    //demo: db_replace_all('fa_ttt', ['admin_id'=>1, 'cat_id'=>1], ['updatetime'=>time()]);
    public static function db_replace_row($table, $insert_data, $update_data){
        if(!is_array($insert_data) || count($insert_data)<=0) return false;
        $field_str = $value_str = $update_field_str = [];
        foreach($insert_data as $k=>$v){
            $field_str[] = $k;
            $value_str[] = "'$v'";
        }
        $field_str = implode(',', $field_str);
        $value_str = implode(',', $value_str);
        foreach($update_data as $k=>$v){
            $update_field_str[] = "$k='{$v}'";
        }
        $update_field_str = implode(',', $update_field_str);
        $sql = "INSERT INTO {$table}({$field_str})"." VALUE({$value_str}) "." ON DUPLICATE KEY UPDATE {$update_field_str}";
        return db()->execute($sql);
    }
    //插入多行记录,存在则替换
    //demo: db_replace_all('fa_ttt',[['admin_id'=>1, 'cat_id'=>1],['admin_id'=>2, 'cat_id'=>2],], ['updatetime']);
    public static function db_replace_all($table, $insert_data, $update_data){
        if(!is_array($insert_data) || count($insert_data)<=0) return false;
        $field_str = $value_str = $update_field_str = '';
        foreach($insert_data as $k=>$v){
            $field_str = implode(',',  array_keys($v) );
            $value_str .= "(".implode(',',  array_values($v) )."),";
        }
        $value_str = rtrim($value_str, ',');
        foreach($update_data as $kk=>$vv){
          $update_field_str .= "$vv=values($vv),";
        }
        $update_field_str = rtrim($update_field_str, ',');
        $sql = "INSERT INTO {$table}({$field_str})"." VALUES {$value_str} "." ON DUPLICATE KEY UPDATE {$update_field_str}";
        return db()->execute($sql);
    }
    //插入记录,存在则不插入
    //demo: db_replace_all('fa_ttt', ['admin_id'=>1, 'cat_id'=>1], ['updatetime'=>time()]);
    public static function db_insert_or($table, $insert_data, $update_data){
        if(!is_array($insert_data) || count($insert_data)<=0) return false;
        $field_str = $value_str = $update_field_str = $update_value_str = [];
        foreach($insert_data as $k=>$v){
            $field_str[] = $k;
            $value_str[] = "'$v'";
        }
        $field_str = implode(',', $field_str);
        $value_str = implode(',', $value_str);
        foreach($update_data as $k=>$v){
            $update_field_str[] = "$k";
            $update_value_str[] = " AND $k='{$v}' ";
        }
        $update_field_str = implode(',', $update_field_str);
        $update_value_str = implode('', $update_value_str);
        $sql = "INSERT INTO {$table}($field_str) SELECT {$value_str} FROM DUAL ".
               "WHERE NOT EXISTS(SELECT {$update_field_str} FROM {$table} WHERE 1 {$update_value_str})";
        return db()->execute($sql);
    }
    //插入多行记录
    public static function db_add_all($table, $data){
        return db($table)->data($data)->insertAll();
    }
    //更新单行记录
    public static function db_edit_row($table, $data, $where){
        return db($table)->strict(false)->where($where)->update($data);
    }
    //生成where in条件
    public static function db_where_in($field, $items){
        if(is_array($items)){
            // $where_str = !empty($items) ? implode(',', $items) : "''";
            $where_str = !empty($items) ? "'".join("','", array_values($items) )."'" : "''"; 
            return $field." IN($where_str) ";
        }
        $where_str = !empty($items) ? $items : "''";
        return $field." IN($where_str) ";
    }
    //------ end ------ //

    /**
     * 数组操作快捷方法 --- start --- //
     */
    public static function arr_all($arr, $key, $val){
        $res = [];
        foreach ($arr as $k => $v) {
            if($v[$key] == $val) $res[] = $v;
        }
        return $res;
    }
    public static function arr_row($arr, $key, $val){
        $res = [];
        foreach ($arr as $k => $v) {
            if($v[$key] == $val) return $v;
        }
        return $res;
    }
    public static function arr_field($arr, $key, $val, $field=''){
        foreach ($arr as $k => $v) {
            if( $v[$key] == $val && isset($v[$field]) ) return $v[$field];
        }
        return '';
    }
    //------ end ------ //



    /**
     * 相关业务/配置 --- start --- //
     */

    public static function banner_list(){
        return \think\Config::get('project.banner');
    }
    //平台类型
    public static function platform_type(){
        return \think\Config::get('project.plat_type');
    }
    //平台列表
    public static function platform_list(){
        return \think\Config::get('project.plat_list');
    }
    //检测平台的状态(是否关闭)
    public static function check_platform_status($val){
        $list = platform_list();
        $row  = arr_row($list, 'key', $val);
        if(@$row['status'] == 1) return true;
        return false;
    }
    //获取平台信息
    public static function platform_name($key, $field='name'){
        $list = platform_list();
        $row  = arr_row($list, 'key', $key);
        return isset($row[$field]) ? $row[$field] : '';
    }

    //头像列表
    public static function avatar_list(){
        return \think\Config::get('project.avatar');
    }

    //支付方式
    public static function payment_list(){
        return \think\Config::get('project.payment');
    }
    //银行卡列表
    public static function bank_list(){
        return \think\Config::get('project.bank');
    }

    //获取红利说明
    public static function bonus_name($key, $field='name'){
        $list = \think\Config::get('project.bonus');
        $row  = arr_row($list, 'key', $key);
        return isset($row[$field]) ? $row[$field] : '';
    }
    //------ end ------ //


}